package com.lez.flowpractice2.fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.lez.flowpractice2.databinding.FragmentNumberBinding
import com.lez.flowpractice2.viewmodel.NumberViewModel
import kotlinx.coroutines.flow.collect

class NumberFragment : Fragment() {

    private val mBinding: FragmentNumberBinding by lazy {
        FragmentNumberBinding.inflate(layoutInflater)
    }
    private val numberViewModel by viewModels<NumberViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return mBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mBinding.apply {
            plusBtn.setOnClickListener {
                numberViewModel.increment()
            }
            reduceBtn.setOnClickListener {
                numberViewModel.decrement()
            }
        }
        lifecycleScope.launchWhenCreated {
            numberViewModel.numberStateFlow.collect { value->
                Log.i("info","哈哈哈哈:"+value)
                mBinding.resultTextView.text = "${value}"
            }
        }
    }
}